const { getRoomList, getRoomGiftInfo, getAreaList } = require('../services/bilibili');
const { isRedPocketExpired, isAnchorExpired } = require('../utils');

const MAX_COCURRENT_REQUEST_COUNT = 50;

// 当前包含红包的房间列表
let ActivateRedPocketRoomList = [];
// 当前包含天选礼物的房间列表
let ActivateAnchorRoomList = [];
// 轮询间隔
const IntervalTime = 5000;
// 单次轮询房间数量
const SingleFetchRoomCount = 500;
// 定时器ID
let IntervalID;
// 当前页码
let CurrentPage = 1;
// 类目
let AreaList = [];
// 当前主类目
let CurrentMainArea;

async function pollFetchBilibiliLiveList(roomCount) {
    const params = {
        platform: 'web',
        parent_area_id: CurrentMainArea.id,
        sort_type: 'online',
        // 初始页码为 1
        page: 1,
    };

    const resultMap = new Map();
    const fetchPageCount = roomCount / 20;

    console.log(`当前类目，${CurrentMainArea.name} ${CurrentMainArea.id} ${CurrentPage}-${CurrentPage + fetchPageCount}`);

    // 构造所有请求的 Promise 对象数组
    const requestPromises = [];
    try {
        for (let i = CurrentPage; i < CurrentPage + fetchPageCount; i++) {
            requestPromises.push(getRoomList({ ...params, page: i }));
        }

        CurrentPage = CurrentPage + fetchPageCount + 1;

        // 等待所有请求完成
        const liveListArray = await Promise.all(requestPromises);

        // 将所有直播信息存储到 resultMap 中
        for (const liveList of liveListArray) {
            for (const live of liveList) {
                resultMap.set(live.roomid, live);
            }
        }
    } catch {
        console.error('部分请求失败');
    }

    // 返回 resultMap
    return resultMap;
}

const changeCurrentArea = () => {
    CurrentPage = 1;
    currentMainAreaIndex = AreaList.findIndex(i => i.id === CurrentMainArea.id);
    if (currentMainAreaIndex < AreaList.length - 1) {
        CurrentMainArea = AreaList[currentMainAreaIndex + 1];
    } else {
        CurrentMainArea = AreaList[0];
    }
}

const getAvaliableRoomList = async () => {
    const roomListStartTime = new Date().valueOf();
    const resultMap = await pollFetchBilibiliLiveList(SingleFetchRoomCount);
    const roomListEndTime = new Date().valueOf();

    const list = Array.from(resultMap.values());

    if (list.length === 0) {
        changeCurrentArea();
        console.log('切换类目');
        console.log(CurrentMainArea.name);
    }

    // console.log(`查询房间列表耗时 ${roomListEndTime - roomListStartTime} ms, 共获取到 ${list.length} 个房间`);

    const requestPromises = [];
    let concurrent = 0;
    let startIndex = 1;
    while (startIndex < list.length) {
        const endIndex = Math.min(startIndex + MAX_COCURRENT_REQUEST_COUNT, list.length);
        const currentList = list.slice(startIndex, endIndex);
        const currentPromises = currentList.map(item => getRoomGiftInfo({ roomid: item.roomid, room: item }));
        requestPromises.push(...currentPromises);
        await Promise.all(currentPromises);
        concurrent = 0;
        startIndex = endIndex;
    }
    const responseList = await Promise.all(requestPromises);
    const hasRedPocketRoomList = responseList.filter(info => info && info.data && info.data.popularity_red_pocket);
    const hasAnchorRoomList = responseList.filter(info => info && info.data && info.data.anchor);

    const roomGiftInfoEndTime = new Date().valueOf();
    // console.log(`查询房间礼物详情耗时 ${roomGiftInfoEndTime - roomListEndTime} ms`);
    return [hasRedPocketRoomList, hasAnchorRoomList];
}

const intervalFetchFunc = async () => {
    const [redPocketRoomList, anchorRoomList] = await getAvaliableRoomList();
    // 判断红包房间是否过期
    const redPocketMap = {};
    const anchorMap = {};
    ActivateRedPocketRoomList = [...ActivateRedPocketRoomList, ...redPocketRoomList].filter(room => {
        if (redPocketMap[room.roomid]) {
            return false;
        }
        redPocketMap[room.roomid] = true;
        return !isRedPocketExpired(room);
    });
    ActivateAnchorRoomList = [...ActivateAnchorRoomList, ...anchorRoomList].filter(room => {
        if (anchorMap[room.roomid]) {
            return false;
        }
        anchorMap[room.roomid] = true;
        return !isAnchorExpired(room);
    });

    console.log(`更新完成，当前红包池 ${ActivateRedPocketRoomList.length} 个，天选池 ${ActivateAnchorRoomList.length} 个`);
}

const startInterval = async () => {
    // 1. 先获取类目
    AreaList = (await getAreaList({
        source_id: 2
    })).filter(area => {
        return [1,5,9].includes(area.id);
    });
    CurrentMainArea = AreaList[0];
    if (IntervalID) {
        clearInterval(IntervalID);
    }
    intervalFetchFunc();
    IntervalID = setInterval(intervalFetchFunc, IntervalTime);
}

const endInterval = () => {
    if (IntervalID) {
        clearInterval(IntervalID);
    }
    IntervalID = null;
}

const getRedPocketRoomList = () => {
    return ActivateRedPocketRoomList;
}

const getAnchorPocketRoomList = () => {
    return ActivateAnchorRoomList;
}

module.exports = {
    getRedPocketRoomList,
    getAnchorPocketRoomList,
    startInterval,
    endInterval,
}